<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户角色关联管理</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .search-container {
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .add-btn {
      margin-left: 10px;
    }
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
    .operation-cell {
      white-space: nowrap;
    }
  </style>
</head>
<body>
<div class="container mt-4">
  <h2>用户角色关联管理</h2>

  <!-- 搜索和新增区域 -->
  <div class="search-container">
    <div class="input-group" style="width: 300px;">
      <input type="text" id="searchId" class="form-control" placeholder="请输入关联ID查询">
      <button class="btn btn-primary" id="searchBtn">查询</button>
      <button class="btn btn-secondary" id="resetBtn">重置</button>
    </div>
    <button class="btn btn-success add-btn" id="addBtn">新增关联</button>
  </div>

  <!-- 表格区域 -->
  <table class="table table-striped table-hover">
    <thead>
    <tr>
      <th>关联ID</th>
      <th>用户ID</th>
      <th>角色ID</th>
      <th>创建时间</th>
      <th>更新时间</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody id="roleTableBody">
    <!-- 数据将通过AJAX动态加载 -->
    </tbody>
  </table>

  <!-- 分页区域 -->
  <div class="pagination-container">
    <nav aria-label="Page navigation">
      <ul class="pagination" id="pagination">
        <!-- 分页将通过JS动态生成 -->
      </ul>
    </nav>
  </div>

  <!-- 新增/编辑模态框 -->
  <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="modalTitle">新增用户角色关联</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="editForm">
            <input type="hidden" id="editId">
            <div class="mb-3">
              <label for="userId" class="form-label">用户ID</label>
              <input type="text" class="form-control" id="userId" required>
            </div>
            <div class="mb-3">
              <label for="roleId" class="form-label">角色ID</label>
              <input type="text" class="form-control" id="roleId" required>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" id="saveBtn">保存</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  $(document).ready(function() {
    // 初始化模态框
    const editModal = new bootstrap.Modal(document.getElementById('editModal'));

    // 当前页码和每页大小
    let currentPage = 1;
    const pageSize = 10;

    // 初始化加载数据
    loadRoleData(currentPage, pageSize);

    // 查询按钮点击事件
    $('#searchBtn').click(function() {
      currentPage = 1;
      loadRoleData(currentPage, pageSize);
    });

    // 重置按钮点击事件
    $('#resetBtn').click(function() {
      $('#searchId').val('');
      currentPage = 1;
      loadRoleData(currentPage, pageSize);
    });

    // 新增按钮点击事件
    $('#addBtn').click(function() {
      $('#modalTitle').text('新增用户角色关联');
      $('#editForm')[0].reset();
      $('#editId').val('');
      editModal.show();
    });

    // 保存按钮点击事件
    $('#saveBtn').click(function() {
      const id = $('#editId').val();
      const userId = $('#userId').val().trim();
      const roleId = $('#roleId').val().trim();

      if (!userId || !roleId) {
        alert('请填写完整的用户ID和角色ID');
        return;
      }

      const data = {
        userId: userId,
        roleId: roleId
      };

      let url = '/sysUserRole/add';
      let method = 'POST';

      // 如果有ID，则是编辑操作
      if (id) {
        data.id = id;
        url = '/sysUserRole/update';
        method = 'PUT';
      }

      $.ajax({
        url: url,
        type: method,
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function(response) {
          if (response.success) {
            alert(response.message);
            editModal.hide();
            loadRoleData(currentPage, pageSize);
          } else {
            alert(response.message || '操作失败');
          }
        },
        error: function(xhr, status, error) {
          alert('请求出错: ' + error);
        }
      });
    });

    // 回车键触发查询
    $('#searchId').keypress(function(e) {
      if (e.which === 13) {
        currentPage = 1;
        loadRoleData(currentPage, pageSize);
      }
    });

    // 加载角色数据
    function loadRoleData(page, size) {
      const searchId = $('#searchId').val().trim();

      // 构建请求参数
      const params = {
        current: page,
        size: size
      };

      // 如果有搜索ID，添加到参数中
      if (searchId) {
        params.id = searchId;
      }

      // 显示加载中
      $('#roleTableBody').html('<tr><td colspan="6" class="text-center">加载中...</td></tr>');

      // AJAX请求
      $.ajax({
        url: '/sysUserRole/page',
        type: 'GET',
        data: params,
        success: function(response) {
          if (response.success) {
            renderTable(response.data.records);
            renderPagination(response.data);
          } else {
            alert('获取数据失败: ' + (response.message || ''));
            $('#roleTableBody').html('<tr><td colspan="6" class="text-center">获取数据失败</td></tr>');
          }
        },
        error: function(xhr, status, error) {
          alert('请求出错: ' + error);
          $('#roleTableBody').html('<tr><td colspan="6" class="text-center">请求出错</td></tr>');
        }
      });
    }

    // 渲染表格数据
    function renderTable(data) {
      let html = '';

      if (data && data.length > 0) {
        data.forEach(function(item) {
          html += `
                            <tr>
                                <td>${item.id || ''}</td>
                                <td>${item.userId || ''}</td>
                                <td>${item.roleId || ''}</td>
                                <td>${formatDate(item.createTime) || ''}</td>
                                <td>${formatDate(item.updateTime) || ''}</td>
                                <td class="operation-cell">
                                    <button class="btn btn-sm btn-primary edit-btn" data-id="${item.id}">编辑</button>
                                    <button class="btn btn-sm btn-danger delete-btn" data-id="${item.id}">删除</button>
                                </td>
                            </tr>
                        `;
        });
      } else {
        html = '<tr><td colspan="6" class="text-center">暂无数据</td></tr>';
      }

      $('#roleTableBody').html(html);

      // 绑定编辑按钮事件
      $('.edit-btn').click(function() {
        const id = $(this).data('id');
        $.ajax({
          url: '/sysUserRole/detail/' + id,
          type: 'GET',
          success: function(response) {
            if (response.success) {
              $('#modalTitle').text('编辑用户角色关联');
              $('#editId').val(response.data.id);
              $('#userId').val(response.data.userId);
              $('#roleId').val(response.data.roleId);
              editModal.show();
            } else {
              alert(response.message || '获取详情失败');
            }
          },
          error: function(xhr, status, error) {
            alert('请求出错: ' + error);
          }
        });
      });

      // 绑定删除按钮事件
      $('.delete-btn').click(function() {
        if (confirm('确定要删除这条记录吗？')) {
          const id = $(this).data('id');
          $.ajax({
            url: '/sysUserRole/delete/' + id,
            type: 'DELETE',
            success: function(response) {
              if (response.success) {
                alert(response.message);
                loadRoleData(currentPage, pageSize);
              } else {
                alert(response.message || '删除失败');
              }
            },
            error: function(xhr, status, error) {
              alert('请求出错: ' + error);
            }
          });
        }
      });
    }

    // 渲染分页
    function renderPagination(pageInfo) {
      let html = '';
      const totalPages = pageInfo.pages;
      const current = pageInfo.current;

      // 上一页按钮
      html += `<li class="page-item ${current === 1 ? 'disabled' : ''}">
                            <a class="page-link" href="javascript:void(0);" data-page="${current - 1}">上一页</a>
                        </li>`;

      // 页码按钮
      const maxVisiblePages = 5; // 最多显示5个页码
      let startPage = Math.max(1, current - Math.floor(maxVisiblePages / 2));
      let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

      // 调整起始页码，确保显示maxVisiblePages个页码
      if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
      }

      // 第一页
      if (startPage > 1) {
        html += `<li class="page-item">
                                <a class="page-link" href="javascript:void(0);" data-page="1">1</a>
                            </li>`;
        if (startPage > 2) {
          html += `<li class="page-item disabled">
                                    <span class="page-link">...</span>
                                </li>`;
        }
      }

      // 中间页码
      for (let i = startPage; i <= endPage; i++) {
        html += `<li class="page-item ${i === current ? 'active' : ''}">
                                <a class="page-link" href="javascript:void(0);" data-page="${i}">${i}</a>
                            </li>`;
      }

      // 最后一页
      if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
          html += `<li class="page-item disabled">
                                    <span class="page-link">...</span>
                                </li>`;
        }
        html += `<li class="page-item">
                                <a class="page-link" href="javascript:void(0);" data-page="${totalPages}">${totalPages}</a>
                            </li>`;
      }

      // 下一页按钮
      html += `<li class="page-item ${current === totalPages ? 'disabled' : ''}">
                            <a class="page-link" href="javascript:void(0);" data-page="${current + 1}">下一页</a>
                        </li>`;

      $('#pagination').html(html);

      // 分页按钮点击事件
      $('.page-link').click(function() {
        const page = $(this).data('page');
        if (page && page !== currentPage) {
          currentPage = page;
          loadRoleData(currentPage, pageSize);
        }
      });
    }

    // 格式化日期
    function formatDate(timestamp) {
      if (!timestamp) return '';
      const date = new Date(timestamp);
      return date.toLocaleString();
    }
  });
</script>
</body>
</html>